class List {
  constructor() {
    this.$ul = $("ul");
    this.init().then(() => {
      this.addToCart();
    });
    // this.addToCart()
  }
  init() {
    return new Promise(resolve => {
      $.get(
        "http://www.xiongmaoyouxuan.com/api/search?word=%E9%98%B2%E8%84%B1%E5%8F%91&start=0&sort=0&couponOnly=NaN&minPrice=0&maxPrice=99999",
        resp => {
          // console.log(resp)
          if (resp.code === 200) {
            console.log(resp);
            resp.data.list.forEach(shop => {
              const li = `
                    <li id="">
                        <img src="${shop.image}" alt="image">
                        <p>${shop.title}</p>
                        <div><span>${shop.price}元</span><i id=${shop.id}>加入购物车</i></div>
                    </li>
                    `;
              const newLi = $(li).appendTo(this.$ul);
              // console.log(newLi)
            });
          }
          resolve();
        }
      );
    });
  }
  addToCart() {
    $("i").on("click", function(e) {
      let cart = window.localStorage.getItem("cart");
      const id = this.id;
      const num = 1;
      const price = parseFloat(
        $(this)
          .prev()
          .text()
      );
      const title = $(this)
        .parent()
        .prev()
        .text();
      cart = JSON.parse(cart);
      console.log(id, price, title);
      console.log(cart);
      if (cart) {
        console.log(1);
        let shopFlag = true;
        cart.forEach(shop => {
          if (shop.id === id) {
            shop.num++;
            shopFlag = false;
          }
        });
        if (shopFlag) {
          cart.push({
            title,
            id,
            num,
            price
          });
        }
        window.localStorage.setItem("cart", JSON.stringify(cart));
      } else {
        window.localStorage.setItem(
          "cart",
          JSON.stringify([
            {
              title,
              id,
              num,
              price
            }
          ])
        );
      }
      alert('ok')
    });
  }
}
new List();
